package com.example.demo.common;
 
import java.security.KeyFactory;
import java.security.KeyPair;
import java.security.KeyPairGenerator;
import java.security.interfaces.RSAPrivateKey;
import java.security.interfaces.RSAPublicKey;
//import java.util.Base64;
import java.util.HashMap;
import java.util.Map;

import javax.crypto.Cipher;

import org.apache.tomcat.util.codec.binary.Base64;

public class RSAUtils {

	public static final String CHARSET_STRING="UTF-8";
	public static final String KEY_ALGORITHM="RSA";
	
	private static byte[] rsaSplitCodec(Cipher cipher,int mode,byte[] data,int keySize) {
		return null;
	}
	
	public static Map<String, Object> genKeyPair(int keySize) throws Exception {
        KeyPairGenerator keyPairGen = KeyPairGenerator.getInstance(KEY_ALGORITHM);
        keyPairGen.initialize(keySize);
        KeyPair keyPair = keyPairGen.generateKeyPair();
        RSAPublicKey publicKey = (RSAPublicKey) keyPair.getPublic();
        String publicKeyString=Base64.encodeBase64URLSafeString(publicKey.getEncoded());
        RSAPrivateKey privateKey = (RSAPrivateKey) keyPair.getPrivate();
        String privateKeyString=Base64.encodeBase64URLSafeString(privateKey.getEncoded());
        Map<String, Object> keyMap = new HashMap<String, Object>();
        //keyMap.put("publickKey", publicKey);
        //keyMap.put("privateKey", privateKey);
        keyMap.put("publickKey", publicKeyString);
        keyMap.put("publickKey", privateKeyString);
        return keyMap;
    }
	
	public static String EncryptPublicKey(String data,RSAPublicKey publicKey)  {
		try {
			Cipher cipher=Cipher.getInstance(KEY_ALGORITHM);
			cipher.init(Cipher.ENCRYPT_MODE, publicKey);
			return Base64.encodeBase64URLSafeString(rsaSplitCodec(cipher,Cipher.ENCRYPT_MODE,data.getBytes(CHARSET_STRING),publicKey.getModulus().bitLength()));
		}
		catch(Exception ex) {			 
			throw new RuntimeException("加密字符串 "+data+" 时遇到错误",ex);
		}
	}
	 
 
}
